package com.sitech.portal.bigScreen.service.impl;

import com.sitech.ibnms.core.IPage;
import com.sitech.ibnms.core.PageForm;
import com.sitech.portal.bigScreen.dao.ScreenPhysicalDao;
import com.sitech.portal.bigScreen.domain.TbScreenPhysical;
import com.sitech.portal.bigScreen.form.TbScreenPhysicalForm;
import com.sitech.portal.bigScreen.service.IScreenPhysicalService;
import org.apache.commons.lang.StringUtils;

import java.util.*;

/**
 * Created by Administrator on 2015/4/22.
 */
public class ScreenPhysicalServiceImpl implements IScreenPhysicalService {
    private ScreenPhysicalDao screenPhysicalDao;
    @Override
    public void addOrUpdateScreenPhysical(TbScreenPhysicalForm tbScreenPhysical,List<String> logicalIds) {
        if(StringUtils.isNotEmpty(tbScreenPhysical.getPhysicalScreenId())){
            screenPhysicalDao.updateScreenPhysical(tbScreenPhysical.toDomain());
            screenPhysicalDao.unrelatedScreenLogicalToPhysical(tbScreenPhysical.getPhysicalScreenId());
            relatedScreenLogicalToPhysical(tbScreenPhysical.getPhysicalScreenId(),logicalIds);
        }else{
            tbScreenPhysical.setPhysicalScreenId(UUID.randomUUID().toString());
            screenPhysicalDao.addScreenPhysical(tbScreenPhysical.toDomain());
            relatedScreenLogicalToPhysical(tbScreenPhysical.getPhysicalScreenId(),logicalIds);
        }
    }

    @Override
    public IPage queryScreenPhysicalByFilter(String name, PageForm pageForm) {
        return screenPhysicalDao.queryScreenPhysicalByFilter(name, pageForm);
    }

    @Override
    public void deleteScreenPhysicalById(String ids) {
        if(StringUtils.isNotEmpty(ids)){
            String[] idArray=ids.split("!!");
            for (String id : idArray) {
                this.screenPhysicalDao.deleteScreenPhysicalById(id);
                screenPhysicalDao.unrelatedScreenLogicalToPhysical(id);
            }
        }
    }

    public void setScreenPhysicalDao(ScreenPhysicalDao screenPhysicalDao) {
        this.screenPhysicalDao = screenPhysicalDao;
    }

    private void relatedScreenLogicalToPhysical(String physicalScreenId, List<String> logicalScreenIdList) {
        if(StringUtils.isNotEmpty(physicalScreenId)){
            int i=0;
            for (String logicalScreenId : logicalScreenIdList) {
                Map<String,Object> param=new HashMap<String, Object>();
                param.put("PHYSICAL_SCREEN_ID",physicalScreenId);
                param.put("LOGICAL_SCREEN_ID",logicalScreenId);
                param.put("SEQ",i);
                this.screenPhysicalDao.relatedScreenLogicalToPhysical(param);
                i++;
            }
        }
    }

    @Override
    public boolean ifNameExist(TbScreenPhysicalForm tbScreenLogical) {
        return screenPhysicalDao.ifNameExist(tbScreenLogical.toDomain());
    }
}
